package cn.rocksolid.sport.common.ds.plugins;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.sql.*;

@MappedTypes(JSONObject.class)
@MappedJdbcTypes(JdbcType.BLOB)
public class JsonObjectBlobTypeHandler extends BaseTypeHandler<JSONObject> {

  private static final JSONObject EMPTY = new JSONObject();

  @Override
  public void setNonNullParameter(PreparedStatement ps, int i, JSONObject jsonObject, JdbcType jdbcType)
          throws SQLException {
    ByteArrayInputStream bis = new ByteArrayInputStream(jsonObject.toJSONString().getBytes(StandardCharsets.UTF_8));
    ps.setBinaryStream(i, bis, bis.available());
  }

  @Override
  public JSONObject getNullableResult(ResultSet rs, String s) throws SQLException {
    Blob blob = rs.getBlob(s);
    if (null != blob) {
      byte[] buf = blob.getBytes(1L, (int) blob.length());
      return JSON.parseObject(new String(buf));
    }
    return EMPTY;
  }

  @Override
  public JSONObject getNullableResult(ResultSet rs, int i) throws SQLException {
    Blob blob = rs.getBlob(i);
    if (null != blob) {
      byte[] buf = blob.getBytes(1L, (int) blob.length());
      return JSON.parseObject(new String(buf));
    }
    return EMPTY;
  }

  @Override
  public JSONObject getNullableResult(CallableStatement cs, int i) throws SQLException {
    Blob blob = cs.getBlob(i);
    if (null != blob) {
      byte[] buf = blob.getBytes(1L, (int) blob.length());
      return JSON.parseObject(new String(buf));
    }
    return EMPTY;
  }
}
